<?php
class Parser_Html_Picasa extends Parser_Html {

    protected $_title;

    protected $_image;

    protected $_description;

    protected function _get_image_xml_url($html, $url_info)
    {
        $image_id = Arr::get($url_info, 'fragment');
        if ($image_id)
        {
            $reg_ex = '/type":"application\/atom\+xml","href":"([^"]+)' . $image_id . '/';
            $matches = array();
            preg_match_all($reg_ex, $html, $matches);

            if (count($matches[0]) > 0)
            {
                $xml_url = null;
                foreach ($matches[1] as $match)
                {
                    if (strstr($match, '/entry/'))
                    {
                        $xml_url = $match . $image_id;
                        break;
                    }
                }

                return $xml_url;
            }
        }
    }

    protected function _parse_xml($url)
    {
        $link = new Link($url);
        $parser = $link->parser();
        if (!$parser)
        {
            return;
        }

        $data = $parser->select('entry group');

        foreach ($data[0]['children'] as $node)
        {
            switch ($node['name'])
            {
                case 'content':
                    $this->_image = isset($node['attributes']['url']) ? $node['attributes']['url'] : null;
                    break;
                case 'description':
                    $this->_description = Arr::get($node, 'text');
                    break;
                case 'title':
                    $this->_title = Arr::get($node, 'text');
                    break;
            }
        }
    }

    public function __construct($html, $url_info, $url)
    {
        parent::__construct($html, $url_info, $url);

        $xml_url = $this->_get_image_xml_url($html, $url_info);

        if ($xml_url)
        {
            $this->_parse_xml($xml_url);
        }
    }

    public function type()
    {
        return $this->_image ? 'image' : 'link';
    }

    public function title()
    {
        return $this->_image ? $this->_title : parent::title();
    }

    public function description()
    {
        return $this->_image ? $this->_description : parent::description();
    }

    public function image()
    {
        return $this->_image;
    }

}